package com.uzhie.web.controller.websocket;

import com.alibaba.fastjson.JSONObject;
import com.uzhie.web.module.User;
import com.uzhie.util.SessionManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by TangFei on 2018/8/14.
 */
public class SocketPostImpl implements SocketPost {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private SessionManager<User> sessionManager;

    @Override
    public void post(String userID, JSONObject resp) {
        try {
            SessionManager<User>.Session<User> userSession = sessionManager.get(userID);
            Map<String, WebSocketSession> socketSessionMap = userSession.getSocketSessionMap();
            Set<Map.Entry<String, WebSocketSession>> entries = socketSessionMap.entrySet();
            Iterator<Map.Entry<String, WebSocketSession>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String,WebSocketSession> entry = iterator.next();
                String key = entry.getKey();
                WebSocketSession value = entry.getValue();
                String s = JSONObject.toJSONString(resp);
                value.sendMessage(new TextMessage(s));
                logger.info("socket 推送到 " + key + " 的消息为 " + s);
            }
        } catch (NoSuchFieldException e) {
            logger.error(e);
        } catch (IOException e) {
            logger.error(e);
        } catch (NullPointerException e) {
            logger.error(e);
        }
    }

    @Override
    public void postAll(JSONObject resp) {
        List<String> allUserID = sessionManager.getAllUserID();
        for (String s : allUserID) {
            post(s, resp);
        }
    }
}
